import * as React from 'react';
import * as ReactDOM from 'react-dom';

import * as Global from '../TS/Global';
import { DeviceCfg } from './devicecfg';
import * as NavBar from './LeftNavBar';
import * as Loading from './Loading';
import { Login } from './Login';
import { MessageBox } from './messagebox';
import MyCfg = require('./MyCfg');
import { NetCfgList } from './netcfglist';
import { Serial } from './serial';
import { ShView } from './ShView';
import { UpLoad } from './upload';
import { CfgRev } from './CfgRev';
import { TOP, TOPProps } from './top';
import { truncateSync } from 'fs';

// import {myClass} from '../CSS/mycss.css'; import * as MyCfg from './MyCfg';
interface MainProps { };

interface MainState {
  IsTest?: boolean;
  Islogin: boolean;
  Dispalycontent: string;
  Thiscfg: MyCfg.MsgCfg;
  IsGet: boolean;
};

class Main extends React.Component<MainProps,
  MainState> {

  GetCfg(): void {
    console.log("获取数值");
    let promise = new Promise(function (resolve, reject) {

      $.ajax({
        url: "WebService.cgi",

        type: 'post',
        timeout: 10000,
        error: (xhr, status, error) => {
          console.log(xhr);
          console.log(error);
          console.log(status);
          reject(error);
        },
        contentType: "application/x-www-form-urlencoded",
        data: {
          datafrom: "common",
          jsondata: "{\"cmd\":\"GetCfg\"}"

        },
        dataType: "json",
        // dataType: "jsonp", jsonp: "callback", jsonpCallback: "success_jsonpCallback",
        success: (result) => {
          resolve(result);
        }
      });
    });
    promise.then((results: any) => {
      console.log("获取数据成功");
      let control: any = this.refs.loading;
      control.ReciveMsgEvent(this, "close", "");
      MyCfg.mycfg = results;
      this.setState({ Thiscfg: MyCfg.mycfg, IsGet: true });
      //this.forceUpdate();
      // MyCfg.tc = 1; MyCfg.mycfg.Net_cfg = results.Net_cfg; MyCfg.mycfg.Serial_cfg =
      // results.Serial_cfg;
      console.log(results)
    }).catch((errors) => {
      console.log(errors);

      if (!this.state.IsTest)
        this.IntervalProc();
      // let control : any = this.refs.loading; control.ReciveMsgEvent(this, "close",
      // ""); console.log("获取数据失败"); let control_msg : any = this.refs.messagebox;
      // control_msg.ShowError("获取配置信息出错:" + errors);
    }
    );
  }

  SaveCfg(_data: any): void {
    console.log("上传数值");
    let promise = new Promise(function (resolve, reject) {

      $.ajax({
        url: "WebService.cgi",

        type: 'post',
        error: (xhr, status, error) => {
          reject(error);
        },
        contentType: "application/x-www-form-urlencoded",
        data: {
          datafrom: 'common',
          jsondata: JSON.stringify(_data)
        },
        dataType: "json", //dataType: "jsonp", jsonp: "callback", jsonpCallback:
        // "success_jsonpCallback",
        success: (result) => {
          resolve(result);
        }
      });
    });
    promise.then((results) => {
      console.log("保存完成:");
      console.log(results);
      this.IntervalProc();
    }, (errors) => {
      console.log("保存失败:");
      console.log(errors);
      let control_loading: any = this.refs.loading;
      control_loading.ReciveMsgEvent(this, "close", "");
      let control: any = this.refs.messagebox;
      control.ShowError(Global.GetLocal("保存配置信息出错") + errors);
    }).catch();
  }
  //执行命令
  Reboot(): void {
    //应用 配置
    let control: any = this.refs.loading;
    control.ReciveMsgEvent(this, "ShowText", Global.GetLocal("设备重启中"));
    let promise = new Promise(function (resolve, reject) {

      $.ajax({
        url: "WebService.cgi",

        type: 'post',
        error: (xhr, status, error) => {
          reject(error);
        },
        contentType: "application/x-www-form-urlencoded",
        data: {
          datafrom: 'common',
          jsondata: JSON.stringify({ cmd: "Reboot" })
        },
        dataType: "json", //dataType: "jsonp", jsonp: "callback", jsonpCallback:
        // "success_jsonpCallback",
        success: (result) => {
          resolve(result);
        }
      });
    });
    promise.then((results) => {
      console.log("重启命令发送完成:");
      console.log(results);
      this.IntervalProc();
    }, (errors) => {
      console.log("重启命令发送失败:");
      console.log(errors);
      let control_loading: any = this.refs.loading;
      control_loading.ReciveMsgEvent(this, "close", "");
      let control: any = this.refs.messagebox;
      control.ShowError("重启命令发送失败:" + errors);
    }).catch();
  }
  //执行命令
  Factory(): void {
    //应用 配置
    let control: any = this.refs.loading;
    control.ReciveMsgEvent(this, "ShowText", Global.GetLocal("设备重启中"));
    let promise = new Promise(function (resolve, reject) {

      $.ajax({
        url: "WebService.cgi",

        type: 'post',
        error: (xhr, status, error) => {
          reject(error);
        },
        contentType: "application/x-www-form-urlencoded",
        data: {
          datafrom: 'common',
          jsondata: JSON.stringify({ cmd: "Factory" })
        },
        dataType: "json", //dataType: "jsonp", jsonp: "callback", jsonpCallback:
        // "success_jsonpCallback",
        success: (result) => {
          resolve(result);
        }
      });
    });
    promise.then((results) => {
      console.log("重启命令发送完成:");
      console.log(results);
      this.IntervalProc();
    }, (errors) => {
      console.log("重启命令发送失败:");
      console.log(errors);
      let control_loading: any = this.refs.loading;
      control_loading.ReciveMsgEvent(this, "close", "");
      let control: any = this.refs.messagebox;
      control.ShowError("重启命令发送失败:" + errors);
    }).catch();
  }
  //重复获取配置信息
  IntervalProc(): void {
    let promise = new Promise(function (resolve, reject) {

      setTimeout(() => {
        resolve();
      }, 3000);

    });
    promise.then((results) => {
      this.GetCfg();
    }, (errors) => { }).catch();
  }
  mainproc: Global.MyMessageEvent;
  constructor(props: any) {
    Global.SetLocalType($.cookie('Language') ? $.cookie('Language') : "zh");
    super(props);
    MyCfg.InitMemu();
    //设置语言 

    this.state = {
      //设置是否是测试模式 跳过登录
      IsTest: true,
      Islogin: $.cookie('Islogined') === "true" ? true : false,
      Dispalycontent: "0-1",
      Thiscfg: MyCfg.mycfg,
      IsGet: false
    };
    console.log("登陆状态:" + $.cookie('Islogined') + this.state.Islogin);

    console.log(this.state);


    if (this.state.IsTest || this.state.Islogin) {
      this.GetCfg();
    }
    /**处理其他控件发送给main控件的事件 */
    this.mainproc = (source, toname, cmd, obj, ...args) => {

      //main处理
      if (!toname) {
        //导航事件处理
        if (cmd == 'nav') {
          let url = obj as string;
          console.log("显示：" + url);

          if (url == "0-5") {
            //重启
            let confirm: MessageBox = this.refs.confirm as MessageBox;
            confirm.Show();
          }
          else if (url == "2-1") {
            alert("待开发");
          }
          else {
            this.setState({ Dispalycontent: url });
          }

        } else if (cmd == 'updatetolinux') {
          console.log("要上传的数据:" + JSON.stringify(MyCfg.mycfg));
          //应用 配置
          let control: any = this.refs.loading;
          control.ReciveMsgEvent(source, "ShowText", Global.GetLocal("设备重启中"), ...args);

          this.SaveCfg(
            {
              cmd: "SaveCfg",
              json: JSON.stringify(MyCfg.mycfg)
            }
          );
        } else if (cmd == "loginok") {
          //登录
          this.setState({ Islogin: true });
          this.GetCfg();
        } else if (cmd == "Factory") {
          this.Factory();
        }

      } else {
        //跟其他组件通讯
        let control: any = this.refs[toname];
        control.ReciveMsgEvent(source, cmd, obj, ...args);
      }

      // console.log(s.props.displayName); var tmp : any = this.refs["top1"];
      // tmp.mytest("回 调"); this.GetCfg();
    };
  }

  public render(): JSX.Element {
    console.log("更新main");


    //this.GetCfg({cmd: 'getjson'});
    var _btnprops: TOPProps = {
      displayName: "Mybtn1",
      OnMessageSendEvent: this.mainproc
    };
    var _topprops: TOPProps = {
      displayName: "top1",
      OnMessageSendEvent: this.mainproc
    };
    var _commprops: Global.Myprops = {
      OnMessageSendEvent: this.mainproc
    };
    let cc: string = " row";
    let content;
    if (!this.state.IsTest && !this.state.IsGet) {
      content = <div>...</div>;
    }
    else {
      if (this.state.Dispalycontent == "0-0") {
        content = <DeviceCfg cfg={this.state.Thiscfg} {..._commprops} />;
      } else if (this.state.Dispalycontent == "0-1") {


        content = <NetCfgList Cfglist={this.state.Thiscfg.Net_cfg} DNS1={this.state.Thiscfg.DNS1 ? this.state.Thiscfg.DNS1 : "223.5.5.5"} DNS2={this.state.Thiscfg.DNS2 ? this.state.Thiscfg.DNS2 : "114.114.114.114"}
          IsSetDNS={this.state.Thiscfg.IsSetDNS} />;

      } else if (this.state.Dispalycontent == "0-2") {
        content = <ShView />;
      }
      else if (this.state.Dispalycontent == "0-3") {
        content = <CfgRev  {..._commprops} />;
      }
      else if (this.state.Dispalycontent == "0-4") {
        content = <UpLoad />;
      } else if (this.state.Dispalycontent == "0-5") { }
      else if (this.state.Dispalycontent == "2-0") { }
      else if (this.state.Dispalycontent == "2-1") { }

      else {
        let strs: string[] = this
          .state
          .Dispalycontent
          .split('-');
        console.log("显示的是串口:" + strs);
        let tindex: number = Number.parseInt(strs[1]);

        console.log("显示的是串口:" + tindex);
        content = <Serial
          index={tindex}
          serialcfg={MyCfg.mycfg.Serial_cfg[tindex]}
          {..._commprops} />;
      }
    }

    var _loginprops: any = {
      OnMessageSendEvent: this.mainproc
    };
    let login = <Login {..._loginprops} />;
    if (!this.state.IsTest && this.state.Islogin == false) {
      return login;
    }

    return (

      <div className="container-fluid ">
        <MessageBox
          ref="confirm"
          MessageType='confirm'
          Title={Global.GetLocal("警告")}
          Content={Global.GetLocal("确认重启设备吗")}
          Ok={() => {
            this.Reboot()
          }} />
        <TOP ref='top1' {..._topprops} />
        <MessageBox
          ref="messagebox"
          MessageType='alert'
          Title={Global.GetLocal("提醒")}
          Content={Global.GetLocal("保存配置成功")} />
        <Loading.Loading
          ref="loading"
          ShowText={Global.GetLocal("加载中")}
          IsShow={this.state.IsTest
            ? false
            : true} />
        <div className="row ">

          <div className="col-xs-12 col-sm-2 ">
            <NavBar.LeftNavBar ref='nav' MenuList={MyCfg.MenuListtest} {..._commprops} /> {/*<NavBar.LeftNavBar MenuList={MyCfg.MenuListtest} OnMessageSendEvent={((source, toname, cmd, obj, ...args) =>this.mainproc(source, toname, cmd, obj, args))}/>*/}
          </div>
          <div className={` `}>
            {content}
            {/*<Netcfg/>*/}

          </div>

        </div>
      </div>
    );
  }
}
export default Main; // var top:TOPProps={ttxx : "速度"}; top.ttxx="哈哈123"; var ttt = // React.createElement(TOP,top)

ReactDOM.render(
  <Main />, document.getElementById('contenter') as HTMLElement, () => { });
